package com.polaris.live.popup

import android.content.Context
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import androidx.activity.ComponentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.adapter.recharge.QuickRechargeAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.util.AppCodeUtils
import com.polaris.live.common.util.DateUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.constant.TrackEventConst.EVENT_RECHARGE_PRICE
import com.polaris.live.constant.TrackEventConst.EVENT_REWARDS_PRICE
import com.polaris.live.constant.TrackEventConst.RECHARGE_FIRST_POPUP
import com.polaris.live.constant.TrackEventConst.RECHARGE_PAGE
import com.polaris.live.constant.TrackEventConst.TRACK_DIALOG
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.PopupRechargeBinding
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.manager.GooglePayManager
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.resp.back_resp.RechargePriceResp
import com.polaris.live.translation.R.string
import com.polaris.live.utils.TrackHelper
import com.polaris.live.viewmodel.GlobalViewModelProxy

/**
 * 充值弹窗
 *
 * @author Created by 半仙 on 2023/10/17/017 9:34
 */
class RechargePopup(
    context: Context,
    private val viewModel: BaseViewModel,
    private var rechargePriceResp: RechargePriceResp,
    private val detail: String? = null,
    private val callTime: Long? = null,
    private val onRechargeBack: ((type: Boolean?) -> Unit),
    private val onDestroyCallback: (() -> Unit)? = null,
    private val isNeedBottom: Boolean,
    private val luckyBagCoins: Long? = null,
) : BottomPopupView(context) {

    private var mTimeCount: TimeCount? = null

    private var mCallTimeCount: CallTimeCount? = null

    private val mAdapter: QuickRechargeAdapter by lazy {
        QuickRechargeAdapter()
    }

    private lateinit var mBinding: PopupRechargeBinding

    private var mRechargeOk: Boolean? = null
    private val mEvent: String
        get() {
            return if (!CollectionUtils.isEmpty(rechargePriceResp.rewardsPriceListVo)) {
                EVENT_REWARDS_PRICE
            } else {
                EVENT_RECHARGE_PRICE
            }
        }

    private val mPage: String
        get() {
            return if (!CollectionUtils.isEmpty(rechargePriceResp.rewardsPriceListVo)) {
                RECHARGE_FIRST_POPUP
            } else {
                RECHARGE_PAGE
            }
        }

    override fun getImplLayoutId(): Int {
        return R.layout.popup_recharge
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupRechargeBinding.bind(popupImplView)

        mBinding.recycler.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
        }
        initData()

        mBinding.userCion.text = UserManager.getUser().account?.userCoins?.toString() ?: "0"
        mBinding.runText.isSelected = true

        if (!TextUtils.isEmpty(detail)) {
            mBinding.runText.text = detail
        } else {
            mBinding.runText.visibility = View.GONE
        }

        if (callTime != null) {
            mCallTimeCount = CallTimeCount((callTime * 1000), 1000)
            mCallTimeCount?.start()
        } else {
            mBinding.llCallTime.visibility = View.GONE
            mBinding.llCallTime2.visibility = View.GONE
        }

        if (luckyBagCoins != null) {
            mBinding.tvLuckyBagCoin.visibility = View.VISIBLE
            mBinding.tvLuckyBagCoin.text = StringUtils.getString(string.diamond_must_how_many, luckyBagCoins.toString())
            mBinding.widgetLucky.visibility = View.VISIBLE
            mBinding.widgetLucky.scaleAnimation()
            mBinding.widgetLucky.registerBagNum(viewModel)
            mBinding.widgetLucky.setPageWidthHeight(35.autoDp, 35.autoDp)
        }

        initListener()

        if (isNeedBottom) {
            val navigationBarHeight = NavigationBarUtils.getNavigationBarHeight(context)
            val layout = mBinding.recycler.layoutParams as LinearLayout.LayoutParams
            layout.bottomMargin = navigationBarHeight
            mBinding.recycler.layoutParams = layout
        }

        //余额变动
        ImNoticeManager.observeAccountChange(this) {
            mBinding.userCion.text = UserManager.getUser().account?.userCoins.toString()
        }
    }

    override fun onDestroy() {
        onDestroyCallback?.invoke()
        super.onDestroy()
    }

    override fun onBackPressed(): Boolean {
        onDestroyCallback?.invoke()
        return super.onBackPressed()
    }

    private fun initListener() {
        mBinding.icClose.setOnSingleClickListener {
            dismiss()
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItem(position)

            val context = context
            val topActivity = if (context is ComponentActivity) {
                context
            } else {
                ViewUtils.getAliveTopActivity() as? ComponentActivity
            } ?: return@setOnItemClickListener

            TrackHelper.postTrack(
                mPage,
                TrackEventConst.EVENT_TOPUP_PC,
                params = TrackHelper.rechargeForMap(mutableMapOf("price" to item.price))
            )
            GooglePayManager.buyShow(topActivity,
                item.priceId,
                UserConst.From.UNKNOWN,
                item.payerRechargeRewardsType,
                price = item.price,
                onSuccess = {
                    GlobalViewModelProxy.getRechargeList(viewModel) {
                        rechargeListSuccess(it)
                    }
                    mRechargeOk = true
                    dismiss()
                },
                onFailure = {
                    mRechargeOk = false

                    ToastGravity.showGravity(it?.message)
                })
        }

        ImNoticeManager.observeAccountChange(this) {
            mBinding.userCion.text = UserManager.getUser().account?.userCoins?.toString() ?: "0"
        }
    }

    private fun initData() {
        if (mTimeCount != null) {
            mTimeCount?.cancel()
            mTimeCount = null
        }

        var startTime = 0L
        if (!CollectionUtils.isEmpty(rechargePriceResp.rewardsPriceListVo)) {
            for (i in 0 until rechargePriceResp.rewardsPriceListVo.size) {
                startTime = rechargePriceResp.rewardsPriceListVo[i].rewardsExp
                break
            }
            mAdapter.setList(rechargePriceResp.rewardsPriceListVo)
        } else {
            for (i in 0 until rechargePriceResp.rechargePriceListVo.size) {
                startTime = rechargePriceResp.rechargePriceListVo[i].rewardsExp
                break
            }
            mAdapter.setList(rechargePriceResp.rechargePriceListVo)
        }

        if (startTime != 0L) {
            mTimeCount = TimeCount(startTime, 1000)
            mTimeCount?.start()
            mBinding.relTitle.visibility = VISIBLE
            mBinding.relCommonTitle.visibility = GONE
        } else {
            mBinding.relTitle.visibility = GONE
            mBinding.relCommonTitle.visibility = VISIBLE
        }
    }

    private fun rechargeListSuccess(resp: RechargePriceResp) {
        rechargePriceResp = resp

        initData()

        mBinding.userCion.text = UserManager.getUser().account?.userCoins?.toString() ?: "0"
    }

    override fun onDismiss() {
        onDestroyCallback?.invoke()
        if (mTimeCount != null) {
            mTimeCount?.cancel()
            mTimeCount = null
        }
        if (mCallTimeCount != null) {
            mCallTimeCount?.cancel()
            mCallTimeCount = null
        }

        onRechargeBack.invoke(mRechargeOk)
        super.onDismiss()
    }

    override fun onShow() {
        LiveStateManager.updateRechargeState(true)
        TrackHelper.postTrack(
            mPage,
            mEvent,
            TRACK_DIALOG,
            mutableMapOf("sourcePage" to TrackHelper.rechargePageMap(context))
        )
        super.onShow()
    }

    internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            val time = DateUtils.formatDuration(millisUntilFinished).convertArabicDigitsToNormal()
            val split = time.split(":")
            if (AppCodeUtils.isAR()) {
                mBinding.timeHour.text = split[2]
                mBinding.timeMinute.text = split[1]
                mBinding.timeSecond.text = split[0]
            } else {
                mBinding.timeHour.text = split[0]
                mBinding.timeMinute.text = split[1]
                mBinding.timeSecond.text = split[2]
            }
        }

        override fun onFinish() {
            GlobalViewModelProxy.getRechargeList(viewModel) {
                rechargeListSuccess(it)
            }
        }
    }

    internal inner class CallTimeCount(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            mBinding.callTimeText.text = "${(millisUntilFinished / 1000)}"
            mBinding.callTimeText2.text = "${(millisUntilFinished / 1000)}"
        }

        override fun onFinish() {

        }
    }
}